package cat.music.ut.component

import android.content.Context
import android.text.Html
import android.text.Spanned
import android.util.Log
import android.view.View
import cat.music.ut.BuildConfig
import com.alibaba.fastjson.JSON
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException

class YUtils {
}

fun dp2px(context: Context, dp: Int): Int {
    val density = context.resources.displayMetrics.density
    return (dp * density).toInt()
}

fun View.click(block: () -> Unit) {
    this.setOnClickListener {
        block.invoke()
    }
}

fun View.show(isShow: Boolean = true) {
    this.visibility = if (isShow) View.VISIBLE else View.GONE
}

fun View.hide() {
    this.visibility = View.GONE
}

fun View.gone() {
    this.visibility = View.GONE
}

fun View.hideAndInvisible() {
    this.visibility = View.INVISIBLE
}

/**
 * debug 模式才会展示日志
 */
fun String?.log(): String? {
    debug {
        Log.e("String.log", "$this")
    }
    return this
}

/**
 * debug 模式才会展示日志
 */
fun String?.log(string: String): String? {
    debug { Log.e(string, "$this") }
    return this
}

fun getResourceNameById(context: Context, resId: Int): String {
    // 使用 Resources 类获取资源名称
    return context.resources.getResourceEntryName(resId)
}

fun String.toHtml(): Spanned {
    return Html.fromHtml(this)
}


val gson = Gson()

/**
 * 转json bean 的通用方法
 */
inline fun <reified T> String?.toJSONBean(): T? {
    return try {
        if (this.isNullOrEmpty()) {
            null
        } else {
            gson.fromJson(this, T::class.java)
        }
    } catch (e: JsonSyntaxException) {
        println("JSON parsing error: ${e.message}")
        null
    }
}

fun Any?.toJSONString(): String {
    return try {
        JSON.toJSONString(this)
    } catch (e: Exception) {
        ""
    }
}

fun debug(block: () -> Unit) {
    if (BuildConfig.DEBUG) {
        block.invoke()
    }
}